package com.safewind.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.safewind.model.AddressGroup;
import com.safewind.model.AllValue;
import com.safewind.model.RestValue;
import com.safewind.model.User;
import com.safewind.service.IAddressGroupService;
import com.safewind.service.IAllValueService;
import com.safewind.service.IRestValueService;
import com.safewind.service.IUserService;
import com.safewind.util.ConstantUtil;
import com.safewind.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private IUserService userService;

	@Resource
	private IAddressGroupService addressGroupService;

	@Resource
	private IAllValueService allValueService;

	@Resource
	private IRestValueService restValueService;

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request, HttpSession session) {
		ModelAndView mav = new ModelAndView();
		String userId = request.getParameter("user_id");
		String password = request.getParameter("password");
		if (checkCode(request.getParameter("code"),
				session.getAttribute("rCode").toString())) {
			mav.setViewName("redirect:/redirect/login");
			session.setAttribute("msg", "codeWrong");
			return mav;
		}
		if (this.login(userId, password)) {
			User user = userService.getUserById(userId);
			if (user.getPkUserId().equals(StringUtil.toMd5(ConstantUtil.ADMIN))) {
				mav.setViewName("redirect:/redirect/admin");
			} else {
				mav.setViewName("redirect:/redirect/homepage");
			}
			session.setAttribute("user", user);
			session.setAttribute("msg", "");
		} else {
			mav.setViewName("redirect:/redirect/login");
			session.setAttribute("msg", "failed");
		}
		return mav;
	}

	private boolean checkCode(String incode, String rightCode) {
		if (incode != null && rightCode != null) {
			if (!incode.equals(rightCode)) {
				return true;
			}
		}
		return false;
	}

	private boolean login(String userId, String password) {
		if (this.check(userId, password)) {
			return true;
		}
		return false;
	}

	private boolean check(String userId, String password) {
		User user = userService.getUserById(userId);
		if (user == null) {
			return false;
		}
		String md5Password = StringUtil.toMd5(password);
		if (!md5Password.equals(user.getPassword())) {
			return false;
		}
		return true;
	}

	@RequestMapping("/reg")
	public ModelAndView reg(HttpServletRequest request, HttpSession session) {
		ModelAndView mav = new ModelAndView();
		String userId = request.getParameter("user_id");
		String password = request.getParameter("password");
		String userName = request.getParameter("user_name");
		String phoneNumber = request.getParameter("phone_number");
		String email = request.getParameter("email");
		if (checkCode(request.getParameter("code"),
				session.getAttribute("rCode").toString())) {
			mav.setViewName("redirect:/redirect/reg");
			session.setAttribute("msg", "codeWrong");
			return mav;
		}
		if (this.checkId(userId)) {
			User user = new User();
			user.setPkUserId(StringUtil.toMd5(userId));
			user.setPassword(StringUtil.toMd5(password));
			user.setUserName(userName);
			user.setPhoneNumber(phoneNumber);
			user.setEmail(email);
			user.setValue(0);
			user.setLastLoginTime(new Date());
			user.setRegisterTime(new Date());
			userService.addUser(user);
			this.addDefaultAddressGroup(user.getPkUserId());
			mav.setViewName("redirect:/redirect/homepage");
			session.setAttribute("user", user);
			session.setAttribute("msg", "");
		} else {
			mav.setViewName("redirect:/redirect/reg");
			session.setAttribute("msg", "failed");
		}
		return mav;
	}

	private void addDefaultAddressGroup(String pkUserId) {
		AddressGroup group = new AddressGroup();
		group.setAddTime(new Date());
		group.setGroupName("默认");
		group.setGroupOrder((byte) 0);
		group.setPkId(StringUtil.getUUID());
		group.setRemark(null);
		group.setUpdateTime(new Date());
		group.setUserId(pkUserId);
		addressGroupService.addGroup(group);
	}

	private boolean checkId(String userId) {
		User user = userService.getUserById(userId);
		if (user == null) {
			return true;
		}
		return false;
	}

	@RequestMapping("/editPassword")
	@ResponseBody
	public Object editPassword(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		String password = request.getParameter("password");
		String newpassword = request.getParameter("newpassword");
		User user = (User) session.getAttribute("user");
		if (user.getPassword().equals(StringUtil.toMd5(password))) {
			user.setPassword(StringUtil.toMd5(newpassword));
			userService.updateUser(user);
			session.setAttribute("user", user);
			map.put("success", true);
		}
		return map;
	}

	@RequestMapping("/getValue")
	@ResponseBody
	public Object getValue(HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User) session.getAttribute("user");
		user = userService.getUserByMD5Id(user.getPkUserId());
		session.setAttribute("user", user);
		map.put("success", true);
		map.put("value", "当前剩余可发送数量为：" + user.getValue() + "条");
		map.put("wx", ConstantUtil.ADMIN_WX);
		map.put("phone", ConstantUtil.ADMIN_PHONE);
		return map;
	}

	@RequestMapping("/getUser")
	@ResponseBody
	public Object getUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		User user = userService.getUserById(id);
		if (user != null) {
			map.put("success", true);
			map.put("id", id);
			map.put("user", user);
		}
		return map;
	}

	@RequestMapping("/editUserValue")
	@ResponseBody
	public Object editUserValue(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		String which = request.getParameter("which");
		String inputNumber = request.getParameter("inputNumber");
		int cost = Integer.parseInt(inputNumber);
		String content = null;
		if (which.equals(ConstantUtil.RECHARGE)) {
			content = "充值";
		} else if (which.equals(ConstantUtil.ENCHASHMENT)) {
			User user = userService.getUserById(id);
			if (user.getValue() < cost) {
				map.put("success", false);
				map.put("msg", "余额不足");
				return map;
			}
			cost = 0 - cost;
			content = "提现";
		}
		userService.updateValue(StringUtil.toMd5(id), cost, content);

		// 历史记录
		AllValue allValue = new AllValue();
		allValue.setPkId(StringUtil.getUUID());
		allValue.setAddTime(new Date());
		allValue.setCost(Integer.parseInt(inputNumber));
		allValue.setContent(content);
		allValue.setUserId(StringUtil.toMd5(id));
		allValueService.insertAllValue(allValue);

		// 总余额更新，如果对象是admin，则代表对总余额操作
		RestValue rv = restValueService.getRestValue();
		if (id.equals(ConstantUtil.ADMIN)) {
			rv.setValue(rv.getValue() + cost);
		} else {
			rv.setValue(rv.getValue() - cost);
		}
		restValueService.updateRestValue(rv);

		// admin更新
		User user = userService.getUserById(ConstantUtil.ADMIN);
		user.setValue(rv.getValue());
		userService.updateUser(user);

		map.put("success", true);
		return map;
	}

	@RequestMapping("/resetPassword")
	@ResponseBody
	public Object resetPassword(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		User user = userService.getUserById(id);
		if (user != null) {
			user.setPassword(StringUtil.toMd5(ConstantUtil.DEFAULT_PASSWORD));
			userService.updateUser(user);
			map.put("msg", "重置密码成功！新密码为：" + ConstantUtil.DEFAULT_PASSWORD);
		} else {
			map.put("msg", "重置密码失败！");
		}
		return map;
	}
}